<!-- ForgetPassword.vue -->
<template>
	<div class="page-container">
		<div class="form-wrapper">
			<h2 class="title">修改密码</h2>
			<van-form @submit="handleSubmit" :validate-trigger="['onChange', 'onSubmit']">
				<!-- 账号输入 -->
				<van-field v-model="form.account" placeholder="请输入注册手机号" left-icon="phone-o" :rules="phoneRules"
					name="account" class="oval-field" />

				<!-- <van-field v-model="form.verification" placeholder="请输入验证码" left-icon="comment-o" class="oval-field"
					name="verification" :rules="[{ required: true, message: '请输入验证码' }]">
					<template #button>
						<van-button size="small" :disabled="countdown > 0" @click="sendSms" class="sms-btn">
							{{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
						</van-button>
					</template>
				</van-field> -->

				<van-field v-model="form.verification" name="verification" placeholder="请输入验证码" left-icon="comment-o"
					class="oval-field" :rules="codeRules">
					<template #button>
						<van-button size="small" :disabled="isCounting" @click="sendCode" native-type="button">
							{{ codeButtonText }}
						</van-button>
					</template>
				</van-field>

				<van-field v-model="form.password" type="password" placeholder="请输入新密码" left-icon="lock"
					class="oval-field" :rules="passwordRules" />

				<van-field v-model="form.confirmPassword" type="password" placeholder="请确认密码" left-icon="lock"
					class="oval-field" :rules="confirmPasswordRules" />

				<van-button block type="primary" native-type="submit" class="oval-btn">
					重置密码
				</van-button>
			</van-form>
			<div class="divider-container">
				<div class="divider-line"></div>
				<span class="divider-text" @click="$router.push('/')">返回登录</span>
				<div class="divider-line"></div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		computed,
		onUnmounted
	} from 'vue'
	import {
		useRouter
	} from 'vue-router'
	import {
		showSuccessToast,
		showFailToast,
		showToast
	} from 'vant'
	import {
		sendVerification,
		resetPassword
	} from '@/api/login'
	import axios from 'axios';

	const router = useRouter()
	const countdown = ref(0)

	const form = ref({
		account: '',
		verification: '',
		password: '',
		confirmPassword: '',
	})

	const phoneRules = [{
		required: true,
		message: '请输入手机号'
	}, {
		pattern: /^1[3-9]\d{9}$/,
		message: '手机号格式错误'
	}]

	const codeRules = [{
		required: true,
		message: '请填写验证码'
	}];
	const passwordRules = [{
		required: true,
		message: '请输入密码'
	}, {
		pattern: /^.{6,8}$/,
		message: '密码需6-8位'
	}];
	const confirmPasswordRules = [{
		required: true,
		message: '请再次输入密码确认'
	}, {
		validator: (value) => value === form.value.password,
		message: '两次输入的密码不一致'
	}];

	const sendSms = async () => {
		if (!form.value.account) return showFailToast('请输入手机号')
		if (!/^1[3-9]\d{9}$/.test(form.value.account)) return showFailToast('手机号格式错误')

		countdown.value = 60
		const timer = setInterval(() => {
			countdown.value--
			if (countdown.value <= 0) clearInterval(timer)
		}, 1000)
	}


	// 验证码倒计时相关
	const countDown = ref(0);
	const isCounting = computed(() => countDown.value > 0);
	const codeButtonText = computed(() =>
		isCounting.value ? `${countDown.value}秒后重发` : '发送验证码'
	);

	let timer = null;


	// 发送验证码
	const sendCode = async () => {
		try {
			// 更严谨的手机号验证（直接使用正则验证）
			if (!/^1[3-9]\d{9}$/.test(form.value.account)) {
				showFailToast('请输入正确的手机号');
				return;
			}

			showToast({
				message: '发送中...',
				forbidClick: true
			});
			const account = {
				account: form.value.account
			};

			const response = await sendVerification(account);

			if (response.status === 200) {
				startCountDown();
				showSuccessToast('验证码已发送');
			} else {
				showFailToast(response.desc || '验证码发送失败');
			}
		} catch (error) {
			// 处理网络错误
			const errorMsg = error.desc || '验证码发送失败';
			showFailToast(errorMsg);
		}
	};
	// 封装倒计时逻辑
	const startCountDown = (seconds = 60) => {
		// 清理已有计时器
		if (timer) clearInterval(timer);

		countDown.value = seconds;
		timer = setInterval(() => {
			countDown.value--;
			if (countDown.value <= 0) {
				clearInterval(timer);
			}
		}, 1000);
	};

	// 组件卸载时清理定时器
	onUnmounted(() => {
		if (timer) clearInterval(timer);
	});

	const handleSubmit = async () => {
		try {

			const response = await resetPassword(form.value);

			if (response.status === 200) {
				showToast({
					type: 'success',
					message: '修改成功',
					forbidClick: true,
					duration: 1000
				});
				setTimeout(() => {
					window.history.back();
				}, 1000)
			} else {
				showFailToast(response.desc || '修改失败');
			}
		} catch (error) {
			// 处理网络错误
			const errorMsg = error.desc || '修改失败';
			showFailToast(errorMsg);
		}
	}
</script>

<style lang="scss" scoped>
	.page-container {
		position: fixed;
		width: 100%;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
		background: linear-gradient(to bottom, #23a6d5, #23d5ab);
		overflow-y: auto;

		.divider-container {
			display: flex;
			align-items: center;
			margin-top: 120px;
		}

		.divider-line {
			flex: 1;
			height: 1px;
			background-color: #dcdfe6;
		}

		.divider-text {
			padding: 0 15px;
			color: white;
			font-size: 14px;
			cursor: pointer;
		}

		/* 从上到下的蓝色渐变 */
		.form-wrapper {
			width: 85%;
			max-width: 400px;

			.title {
				text-align: center;
				margin-bottom: 40px;
				color: white;
				font-size: 24px;
			}

			.oval-field {
				display: flex;
				align-items: center;
				margin-bottom: 20px;
				border-radius: 25px;
				background: #fff;
				opacity: .5;

				//box-shadow: 0 3px 10px rgba(58, 123, 213, 0.1);
				:deep(.van-field__left-icon) {
					margin-left: 15px;
					color: #3a7bd5;
				}

				:deep(.van-field__control) {
					//padding: 12px 0;
				}
			}

			.oval-btn {
				margin-top: 30px;
				border-radius: 25px;
				//background: linear-gradient(45deg, #3a7bd5, #00d2ff);
				background-color: #ffffff;
				color: #23a6d5;
				border: none;
			}

			.link-group {
				margin-top: 20px;
				display: flex;
				justify-content: space-between;
				color: #3a7bd5;
				font-size: 14px;

				span {
					cursor: pointer;
					transition: opacity 0.3s;

					&:hover {
						opacity: 0.8;
					}
				}
			}
		}
	}
</style>